package com.libinyn.base.pms.serivce.impl.sys;


import com.libinyn.base.pms.common.utils.Result;
import com.libinyn.base.pms.config.shiro.TokenGenerator;
import com.libinyn.base.pms.entity.sys.SysUserTokenEntity;
import com.libinyn.base.pms.mapper.sys.SysUserTokenMapper;
import com.libinyn.base.pms.serivce.impl.BaseServiceImpl;
import com.libinyn.base.pms.serivce.sys.SysUserTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


/**
 * 用户token实现类
 * @fileName: SysUserTokenServiceImpl.java
 * @author: bin.li01
 * @date: 2017/12/10 12:11 
 * @version: v1.0.0
 */
@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenEntity> implements SysUserTokenService {

	@Resource
	private SysUserTokenMapper sysUserTokenMapper;
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	
	@Override
	public Result createToken(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
		SysUserTokenEntity sysUserTokenEntity = new SysUserTokenEntity();
		sysUserTokenEntity.setUserId(userId);
		//判断是否生成过token
		SysUserTokenEntity tokenEntity = sysUserTokenMapper.selectOne(sysUserTokenEntity);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			sysUserTokenMapper.insert(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			sysUserTokenMapper.updateByPrimaryKeySelective(tokenEntity);
		}

		Result r = Result.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}

	@Override
	public void logout(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//修改token
		SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(new Date());
		//空值也需要更新，将有效时间更新
		sysUserTokenMapper.updateByPrimaryKey(tokenEntity);
	}
}
